package org.x.datasource.aspect;


import cn.hutool.core.util.StrUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.x.common.base.util.UserContextHolder;
import org.x.datasource.config.DynamicDataSourceContextHolder;

@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DynamicTenantAspect {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(org.x.datasource.anno.DynamicTenant) " +
            "|| @within(org.x.datasource.anno.DynamicTenant)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        String tenantId = UserContextHolder.getTenantId();

        if(StrUtil.isEmpty(tenantId) || "null".equals(tenantId)) {
            throw new RuntimeException("租户ID缺失，需要重新登录！");
        }

        DynamicDataSourceContextHolder.setDataSourceKey(tenantId);

        logger.debug("set datasource is {}", tenantId);

        try {
            return point.proceed();
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceKey();
            logger.debug("clean datasource");
        }
    }
}
